package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.cache.aspect.CacheService;
import com.atguigu.gmall.common.constant.RedisConstant;
import com.atguigu.gmall.feign.list.GoodsFeignClient;
import com.atguigu.gmall.model.list.Goods;
import com.atguigu.gmall.model.list.SearchAttr;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.SkuInfoMapper;
import com.atguigu.gmall.product.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author lfy
* @description 针对表【sku_info(库存单元表)】的数据库操作Service实现
* @createDate 2022-03-05 11:23:36
*/
@Slf4j
@Service
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoMapper, SkuInfo>
    implements SkuInfoService{

    @Resource
    SkuInfoMapper skuInfoMapper;

    @Autowired
    SkuImageService skuImageService;

    @Autowired
    SkuAttrValueService skuAttrValueService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    BaseTrademarkService baseTrademarkService;

    @Autowired
    BaseCategory1Service baseCategory1Service;

    @Autowired
    CacheService cacheService;
    @Autowired
    GoodsFeignClient goodsFeignClient;



    @Transactional
    @Override
    public void saveSkuInfo(SkuInfo skuInfo) {
        //1、给 sku_info 保存数据
        skuInfoMapper.insert(skuInfo);

        Long id = skuInfo.getId();
        Long spuId = skuInfo.getSpuId();

        //2、给 sku_image 保存数据
        List<SkuImage> imageList = skuInfo.getSkuImageList();
        if(imageList !=null && imageList.size() > 0){
            for (SkuImage skuImage : imageList) {
                skuImage.setSkuId(id); //回填skuId
            }
        }
        skuImageService.saveBatch(imageList);

        //3、给  sku_attr_value 保存数据；保存当前sku对应的真正平台属性名和值
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        if(skuAttrValueList!=null && skuAttrValueList.size() > 0){
            for (SkuAttrValue attrValue : skuAttrValueList) {
                attrValue.setSkuId(id);//回填skuId
            }
        }
        skuAttrValueService.saveBatch(skuAttrValueList);

        //4、给 sku_sale_attr_value 保存数据。保存当前sku对应的销售属性名和值
        List<SkuSaleAttrValue> saleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        if(saleAttrValueList!=null && saleAttrValueList.size()>0){
            for (SkuSaleAttrValue saleAttrValue : saleAttrValueList) {
                saleAttrValue.setSkuId(id); //回填skuId
                saleAttrValue.setSpuId(spuId); //回填spuId
            }
        }
        skuSaleAttrValueService.saveBatch(saleAttrValueList);
        log.info("id：【{}】sku信息保存完成：",id);


        //5、给布隆过滤器里面添上这个sku
        RBloomFilter<Object> bloomFilter = cacheService.getBloomFilter(RedisConstant.SKUIDS_BLOOM);
        bloomFilter.add(id);

    }

    @Override
    public void updateSkuSaleStatus(Long skuId, int status) {
        //1、改数据库
        skuInfoMapper.updateSaleStatus(skuId,status);

        if(status == 0){
            //下架
            goodsFeignClient.cancleSaleGoods(skuId);
        }else {
            //上架
            // 操作 ElasticSearch 进行数据增加删除。
            //2、查询SkuInfo的所有详情，并组装成 Goods 这个模型
            Goods goods = getSkuInfoForSearchGoods(skuId);

            //3、远程调用检索服务进行ES上架(ES数据保存)；
            goodsFeignClient.onSaleGoods(goods);
        }
    }

    //查出sku的详细，并封装成 Goods
    private Goods getSkuInfoForSearchGoods(Long skuId) {
        Goods goods = new Goods();

        //1、skuInfo 信息
        SkuInfo info = skuInfoMapper.selectById(skuId);

        goods.setId(info.getId());
        goods.setDefaultImg(info.getSkuDefaultImg());
        goods.setTitle(info.getSkuName());
        goods.setPrice(info.getPrice());
        goods.setCreateTime(new Date());
        goods.setTmId(info.getTmId());

        //2、查询品牌信息
        BaseTrademark trademark = baseTrademarkService.getById(info.getTmId());
        goods.setTmName(trademark.getTmName());
        goods.setTmLogoUrl(trademark.getLogoUrl());

        //3、当前sku所在的完整分类信息
        BaseCategoryView categoryPathBySkuId = baseCategory1Service.getCategoryPathBySkuId(skuId);
        goods.setCategory1Id(categoryPathBySkuId.getCategory1Id());
        goods.setCategory2Id(categoryPathBySkuId.getCategory2Id());
        goods.setCategory3Id(categoryPathBySkuId.getCategory3Id());

        goods.setCategory1Name(categoryPathBySkuId.getCategory1Name());
        goods.setCategory2Name(categoryPathBySkuId.getCategory2Name());
        goods.setCategory3Name(categoryPathBySkuId.getCategory3Name());

        //4、当前sku的平台属性集合（参与检索）
        List<SearchAttr> attrs = skuAttrValueService.getSkuSearchBaseAttrs(skuId);
        goods.setAttrs(attrs);

        //封装结束
        return goods;
    }

    @Override
    public BigDecimal getSkuPrice(Long skuId) {
        return skuInfoMapper.getSkuPrice(skuId);
    }

    @Override
    public List<Long> getAllSkuIds() {
        return skuInfoMapper.getAllSkuIds();
    }

    @Override
    public Map<Long, BigDecimal> batchGetSkuPrice(List<Long> skuIdList) {
        Map<Long, BigDecimal> map = new HashMap<>();
        QueryWrapper<SkuInfo> queryWrapper = new QueryWrapper();
        queryWrapper.select("id","price");
        queryWrapper.in("id",skuIdList);
        List<SkuInfo> infos = skuInfoMapper.selectList(queryWrapper);

        for (SkuInfo info : infos) {
            map.put(info.getId(),info.getPrice());
        }

        return map;
    }
}




